package com.lanbu.system.service.impl;

import java.security.SecureRandom;
import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.lanbu.common.config.KnowledgeProperties;
import com.lanbu.common.constant.DeptConstants;
import com.lanbu.common.constant.FastGptUserConstants;
import com.lanbu.common.core.domain.vo.FastGptOpenapiVo;
import com.lanbu.common.utils.DateUtils;
import com.lanbu.system.domain.SysDeptOpenapi;
import com.lanbu.system.domain.mongo.*;
import com.lanbu.system.mapper.SysDeptOpenapiMapper;
import lombok.RequiredArgsConstructor;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import com.lanbu.common.annotation.DataScope;
import com.lanbu.common.constant.UserConstants;
import com.lanbu.common.core.domain.TreeSelect;
import com.lanbu.common.core.domain.entity.SysDept;
import com.lanbu.common.core.domain.entity.SysRole;
import com.lanbu.common.core.domain.entity.SysUser;
import com.lanbu.common.core.text.Convert;
import com.lanbu.common.exception.ServiceException;
import com.lanbu.common.utils.SecurityUtils;
import com.lanbu.common.utils.StringUtils;
import com.lanbu.common.utils.spring.SpringUtils;
import com.lanbu.system.mapper.SysDeptMapper;
import com.lanbu.system.mapper.SysRoleMapper;
import com.lanbu.system.service.ISysDeptService;

/**
 * 部门管理 服务实现
 *
 * @author lanbu
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements ISysDeptService
{
    private final SysDeptMapper deptMapper;

    private final SysRoleMapper roleMapper;

    private final MongoUsersService mongoUsersService;

    private final MongoTeamMembersService mongoTeamMembersService;

    private final MongoOpenApisService mongoOpenApisService;

    private final KnowledgeProperties knowledgeProperties;

    private final SysDeptOpenapiMapper sysDeptOpenapiMapper;

    private final   MongoTeamsService mongoTeamsService;
    private final   MongoTeamMembersGroupsService mongoTeamMembersGroupsService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    @Override
    public List<SysDept> selectDeptVoList(SysDept dept) {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);

        return depts.stream().map(sysdept -> {
            FastGptOpenapiVo fastGptOpenapiVo = new FastGptOpenapiVo();
            SysDeptOpenapi queryDeptOpenapi = SysDeptOpenapi.builder().deptId(sysdept.getDeptId()).build();
            List<SysDeptOpenapi> sysDeptOpenapis = sysDeptOpenapiMapper.selectSysDeptOpenapiList(queryDeptOpenapi);
            if(ObjectUtil.isNotEmpty(sysDeptOpenapis)){
                SysDeptOpenapi sysDeptOpenapi = sysDeptOpenapis.get(0);

                MongoOpenApis mongoOpenApis = Optional.ofNullable(mongoOpenApisService.findApiKeyById(sysDeptOpenapi.getOpenapiId())).orElse(new MongoOpenApis());
                fastGptOpenapiVo.setId(String.valueOf(mongoOpenApis.get_id()));
                fastGptOpenapiVo.setApiKey(mongoOpenApis.getApiKey());
                fastGptOpenapiVo.setName(mongoOpenApis.getName());
            }
            sysdept.setFastGptOpenapiVo(fastGptOpenapiVo);
            return sysdept;
        }).collect(Collectors.toList());
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId))
        {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态，且父节点不为 0,则不允许新增子节点
        if (!(Long.valueOf(0L).equals(dept.getParentId()) || UserConstants.DEPT_NORMAL.equals(info.getStatus())))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        String ancestors = "0";
        if(!Long.valueOf(0L).equals(dept.getParentId())){
            ancestors = info.getAncestors() + "," + dept.getParentId();
        }
        dept.setAncestors(ancestors);
        //新增客服部门时，判断是否可以修改客服部门
        //一级节点新增时不用判断是否为客服部门
        if (Long.valueOf(0L).equals(dept.getParentId())){
        } else if ("1".equals(dept.getIsService())){
            SysDept sysDept = this.findServiceDepartmentDeptId(dept.getParentId());
            if (sysDept!=null){
                throw new ServiceException("已存在客服部门，不允许新增");
            }
        }

        int result = deptMapper.insertDept(dept);

        // 判断如果是一级节点,则构建与fastGpt的联系 -- 可考虑改为异步
        buildFastGptUser(dept);
        // 构建部门与 openapi 的绑定
        buildDeptBindOpenapi(dept);
        return result;
    }
    //查询客服部门
    private SysDept findServiceDepartmentDeptId(Long deptId) {
        Long id = this.findRootTreeId(deptId);
        List<SysDept> depts = deptMapper.selectAllChildrenDeptById(id);
        if (depts==null){
            return null;
        }
        SysDept dept = null;
        for (int i = 0; i < depts.size(); i++) {
            SysDept dept1 = depts.get(i);
            if ("1".equals(dept1.getIsService())) {
                dept = dept1;
            }
        }
        return dept;
    }


    /**
     * 构建部门与fastGpt的联系
     */
    private void buildFastGptUser(SysDept dept) {
        String ancestors = dept.getAncestors();
        List<String> splitByComma = StrUtil.split(ancestors, ",");
        if(ObjectUtil.isNotNull(splitByComma) && splitByComma.size() != DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
            return;
        }
        // 创建用户与 fastGpt 相关联
        MongoUsers mongoUsers = new MongoUsers();
        mongoUsers.setUsername(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR);
        mongoUsers.setPassword(SecureUtil.sha256(SecureUtil.sha256(dept.getDeptId() + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)));
        mongoUsers.setStatus(FastGptUserConstants.USER_STATUS);
        //mongoUsers.setAvatar(FastGptUserConstants.USER_AVATAR);
        mongoUsers.setPromotionRate(FastGptUserConstants.USER_PROMOTION_RATE_COMMON);
        mongoUsers.setTimezone(FastGptUserConstants.TIME_ZONE);
        mongoUsers.setCreateTime(DateUtils.getNowDate());
        mongoUsers.setVersion(FastGptUserConstants.VERSION);
        MongoUsers users = mongoUsersService.save(mongoUsers);

        // 查出 root 的 teamId
//        MongoUsers root = Optional.ofNullable(mongoUsersService.findByUsername(knowledgeProperties.getRootName())).orElse(new MongoUsers());
//        MongoTeamMembers rootTeamMember = Optional.ofNullable(mongoTeamMembersService.findByUserId(root.getId())).orElse(new MongoTeamMembers());

        MongoTeams teams = new MongoTeams();
        teams.setName(dept.getDeptId()+"-"+dept.getDeptName());
        teams.setCreateTime(DateUtils.getNowDate());
        teams.setVersion(FastGptUserConstants.VERSION);


        teams.setPath("");
        teams.setPathId("twoFcjKLaZu6");

        teams.setTeamId(String.valueOf(users.getId()));
        teams.setOwnerId(String.valueOf(users.getId()));
        teams.setUpdateTime(new Date());
        teams.setCreateAt(new Date());
        teams.setDefaultPermission("0");
        teams.setAvatar("/icon/logo.svg");
        MongoTeams mongoTeams = mongoTeamsService.save(teams);

        // 将新建的用户加入 admin 团队下
        MongoTeamMembers teamMembers = new MongoTeamMembers();
        teamMembers.setAvatar("/imgs/avatar/GrayModernAvatar.svg");
        teamMembers.setTeamId(mongoTeams.getId());
        teamMembers.setUserId(users.getId());

        teamMembers.setName(FastGptUserConstants.TEAM_MEMBER_NAME);
        teamMembers.setRole(FastGptUserConstants.TEAM_MEMBER_NAME_NEW);
        teamMembers.setStatus(FastGptUserConstants.USER_STATUS);
//        teamMembers.setCreateTime(DateUtils.getNowDate());
        teamMembers.setDefaultTeam(true);
        //新增

        teamMembers.setUpdateTime(new Date());
        teamMembers.setCreateAt(new Date());

        mongoTeamMembersService.save(teamMembers);


    }


    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept)
    {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        //要修改客服部门时，判断是否可以修改客服部门
        if ("1".equals(dept.getIsService())){
            SysDept sysDept = this.findServiceDepartmentDeptId(dept.getDeptId());
            //如果是客服部门修改，再可以修改，不是客服部门修改成客服部门，则报错
            if (sysDept!=null&&!sysDept.getDeptId().equals(dept.getDeptId())){
                throw new ServiceException("已存在客服部门，不允许新增");
            }
        }

        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }

        // 构建部门与 openapi 的绑定
        buildDeptBindOpenapi(dept);
        return result;
    }

    private void buildDeptBindOpenapi(SysDept sysDept) {

        FastGptOpenapiVo fastGptOpenapiVo = sysDept.getFastGptOpenapiVo();
        if(ObjectUtil.isEmpty(fastGptOpenapiVo)){
            return;
        }
        String openapi = String.valueOf(fastGptOpenapiVo.getId());

        // 删除原本的绑定关系
        sysDeptOpenapiMapper.deleteSysDeptOpenapiByDeptId(sysDept.getDeptId());
        // 构建新的关系
        SysDeptOpenapi deptOpenapi = SysDeptOpenapi.builder().deptId(sysDept.getDeptId()).openapiId(openapi).build();
        sysDeptOpenapiMapper.insertSysDeptOpenapi(deptOpenapi);
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId)
    {
        delFastGptUser(deptId);
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public Long findRootTreeId(Long parentId) {
        List<SysDept> sysDepts = deptMapper.selectParentId(parentId);
        if (sysDepts==null||sysDepts.size()==0){
            return 0L;
        }
        SysDept dept = sysDepts.get(0);
        if (dept.getParentId()==0L){
            return dept.getDeptId();
        }
        return findRootTreeId(dept.getParentId());
    }

    /**
     * 判断用户的组织是否是管理员和一级组织
     * @param deptId
     * @return
     */
    @Override
    public boolean selectJudgeMenusRole(Long deptId) {
        SysDept sysDept = deptMapper.selectJudgeDeptById(deptId);

        if (sysDept==null){
            return false;
        }
        return true;
    }


    /**
     * 删除部门与fastGpt的联系
     */
    private void delFastGptUser(Long deptId) {
        SysDept sysDept = deptMapper.selectDeptById(deptId);

        // 如果不是 DEPT_UNION_FAST_GPT_DEEP 层级则无绑定关系，不需要处理
        String ancestors = sysDept.getAncestors();
        List<String> splitByComma = StrUtil.split(ancestors, ",");
        if(ObjectUtil.isNotNull(splitByComma) && splitByComma.size() != DeptConstants.DEPT_UNION_FAST_GPT_DEEP){
            return;
        }

        MongoUsers mongoUsers = Optional.ofNullable(mongoUsersService.findByUsername(deptId + DeptConstants.DEPT_UNIQUE_SUFFIX_STR)).orElse(new MongoUsers());
        MongoTeamMembers teamMembers = Optional.ofNullable(mongoTeamMembersService.findByUserId(mongoUsers.getId())).orElse(new MongoTeamMembers());
        if(ObjectUtil.isNotNull(teamMembers.getId())){
            mongoTeamMembersService.deleteById(teamMembers.getId());
        }
        if(ObjectUtil.isNotNull(mongoUsers.getId())){
            mongoUsersService.deleteById(mongoUsers.getId());
        }
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }
}
